// packageA/member/course/VoiceDetail/VoiceDetail.js
var app = getApp();
let innerAudioContext = null;
Page({

  /**
	 * 页面的初始数据
	 */
  data: {
    stop1: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/stop1.png",
    play1: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/play1.png",
    bfstatus: false,
    currentTime: "0:00:00",
    slmin: "0:00:00",
    valueSlmin: 0,
    audio_length: 0,

    article_id: '',
    dataInfo: {
      audio_link: ''
    },
    // innerAudioContext: null,
    isPlay: false,
    // 是否有权限看
    isShow: 1,
    codeUrl: '',
    // 评论功能
    replyName: "",
    commentPage: 1,
    commentList: [],
    last_page: 1,
    commenMember: [],
    keyInd: 0,
    comment_id: 0,
    // commentOn: false,
    comment: false,
    commentNum: 0,
    imgList: [],
    maincomment: "",
    replyContent: "",
    is_liked:0
  },

  /**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function(options) {
    innerAudioContext = wx.createInnerAudioContext();
    if (options.article_id) {
      this.setData({
        article_id: options.article_id
      });
    }
    this.setData({
      options
    })
    this.getData();
    // this.getQrCode();
  },

  /**
	 * 生命周期函数--监听页面初次渲染完成
	 */
  onReady: function() {

  },

  /**
	 * 生命周期函数--监听页面显示
	 */
  onShow: function() {
    this.init();
    if(this.data.options.task_type == 'article'){
      this.shareArticleTask();
    }
  },
  shareArticleTask(){
    let json = {
      record_id:this.data.options.taskID,
      task_type:'article',
      day:this.data.options.taskDay,
      task_record_id:this.data.article_id
    }
    let urlStr = app.getNetAddresss(
      "plugin.task-package.frontend.daily-record.finish-task"
    );
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: json,
      success: function (resdata) {},
      fail: function (res) {},
    });
  },
  /**
	 * 生命周期函数--监听页面隐藏
	 */
  onHide: function() {
    innerAudioContext.stop();
    innerAudioContext.destroy();
  },

  /**
	 * 生命周期函数--监听页面卸载
	 */
  onUnload: function() {
    innerAudioContext.stop();
    innerAudioContext.destroy();
  },

  /**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
  onPullDownRefresh: function() {

  },

  /**
	 * 页面上拉触底事件的处理函数
	 */
  onReachBottom: function() {

  },

  /**
	 * 用户点击右上角分享
	 */
  onShareAppMessage: function() {
    var value = wx.getStorageSync("yz_uid");
    var mid = "";
    if (value) {
      mid = value;
    }
    let json = {
      path: "/packageA/member/course/VoiceDetail/VoiceDetail?article_id=" + this.data.article_id + "&mid=" + mid,
      title: this.data.dataInfo.title,
      imageUrl: this.data.dataInfo.thumb ? this.data.dataInfo.thumb : "",
    }
    if(this.data.options.taskID){
      json.path += `&taskID=${this.data.options.taskID}&taskDay=${this.data.options.taskDay}&task_type=article`
    }
    return json
  },
  audioPlay() {
    if(this.data.isPlay) {
      this.data.isPlay = false;
      this.innerAudioContext.pause();
    }else {
      this.data.isPlay = true;
      this.innerAudioContext.play();
    }
  },
  toAdv: function () {
    console.log("跳转到广告");
    if (!app._isTextEmpty(this.data.dataInfo) && app._isTextEmpty(this.data.dataInfo.min_app_advs_link)) {
      return;
    }
    wx.navigateTo({
      url: this.data.dataInfo.min_app_advs_link,
    });
  },
  clickLike: function () {
    this._toLike();
  },
  toReport: function () {
    wx.navigateTo({
      url: "/packageA/member/article/noticeReport/noticeReport?article_id=" + this.data.article_id,
    });
  },
  toLink: function (e) {
    let url = e.currentTarget.dataset.link;
    wx.navigateTo({
      url: url,
    });
  },
  _toLike: function (success) {
    var that = this;
    // 点赞
    app._getNetWork({
      url: app.getNetAddresss("plugin.article.api.article.like"),
      data: {
        article_id: that.data.article_id,
      },
      success: function (res) {
        if (res.data.result == 1) {
          let _data = res.data.data;
          if (_data.liked == 1) {
            that.setData({
              is_liked: true,
              like_num: that.data.like_num + 1,
            });
            wx.showToast({
              title: "点赞成功",
            });
          } else {
            that.setData({
              is_liked: false,
              like_num: that.data.like_num - 1,
            });
            if (that.data.like_num < 0) {
              that.setData({
                like_num: 0,
              });
            }
            wx.showToast({
              title: "取消点赞",
              icon: "none",
            });
          }

          success && success(res);
        } else {
          console.error(res);
        }
      },
      fail: function (res) {
        console.error(res);
      },
    });
  },
  // 删除评论
  delComment(e) {
    console.log(e);
    let myUid;
    try {
      myUid = wx.getStorageSync('uid');
    } catch (error) {
      myUid = '';
    }
    let item = e.currentTarget.dataset.item;
    let ind = e.currentTarget.dataset.ind;
    let index;
    try {
      index = e.currentTarget.dataset.index;
    } catch (error) {
      index = null;
    }
    console.log(item, ind, index);
    if (this.data.commentList[ind].child.length > 0) {
      if (item.uid == myUid) {
        console.log('子评论是我的，可以删');
        this.delRequst(item.id, ind, index, 'child');
      }
    } else {
      if (myUid == item.uid) {
        console.log('主评论是我的，可以删');
        this.delRequst(item.id, ind, index, 'list');
      }
    }

  },
  watchImg(e) {
    // 评论图片预览
    let item = e.currentTarget.dataset.item;
    wx.previewImage({
      current: item[0], // 当前显示图片的http链接
      urls: item // 需要预览的图片http链接列表
    });
  },
  // 回复
  replyBtn(e) {
    let item = e.currentTarget.dataset.item;
    let name = item.nick_name;
    this.setData({
      keyInd: e.currentTarget.dataset.kind,
      replyshow: true,
      replyId: item.id,
      comment_id: item.comment_id == 0 ? item.comment_id : item.id,
      replyName: name,
      commentManagement: false,
    });
  },
  // 加载子评论
  moreCommentLis(e) {
    console.log(e);
    wx.showLoading({
      title: '加载中',
      icon: 'none',
      duration: 1000
    });
    let that = this;
    let id = e.currentTarget.dataset.item.id;
    let ind = e.currentTarget.dataset.ind;
    let urlStr = "plugin.article.api.comment.get-replys";
    console.log(this.data.commentList);
    let is_page = Number(this.data.commentList[ind].commenMorePage);
    let dataJson = {
      page: is_page,
      comment_id: id,
    };
    app._getNetWork({
      url: app.getNetAddresss(urlStr),
      data: dataJson,
      success: function (res) {
        if (res.data.result == 1) {
          let resdata = res.data.data;
          console.log(resdata);
          let childs = resdata.data;
          let num = that.data.commentList[ind].reply_num - resdata.data.length;
          that.data.commentList[ind].reply_num = num;
          let arr = that.data.commentList[ind].child.concat(childs);
          that.data.commentList[ind].child = arr;
          let moreLast_page = resdata.data.last_page;
          if (is_page >= moreLast_page) {
            is_page = 1;
          } else {
            is_page = is_page + 1;
          }
          that.data.commentList[ind].commenMorePage = is_page;
          that.setData({
            commentList: that.data.commentList,
          });
        } else {
          console.error(res);
        }
        wx.hideLoading({
          success: (res) => {},
        });
      },
      fail: function (res) {
        wx.hideLoading({
          success: (res) => {},
        });
        console.error(res);
      },
    });
  },
  getMore() {
    let that = this;
    this.setData({
      commentPage: this.data.commentPage + 1,
    });
    wx.showLoading({
      title: '加载中',
      duration: 1000,
      icon: 'none'
    });
    app._getNetWork({
      url: app.getNetAddresss("plugin.article.api.comment.comment-list"),
      data: {
        page: this.data.commentPage,
        article_id: this.data.article_id,
      },
      success: function (res) {
        if (res.data.result == 1) {
          let dataMore = res.data.data.list.data;
          for (let i = 0; i < dataMore.length; i++) {
            if (dataMore[i].reply_num > 0) {
              dataMore[i].commentShow = true;
            } else {
              dataMore[i].commentShow = false;
            }
            dataMore[i].commenMorePage = 1;
            dataMore[i].child = [];
          }
          that.setData({
            commentList: that.data.commentList.concat(dataMore),
            last_page: res.data.data.list.last_page,
          });
        } else {
          console.error(res);
        }
        wx.hideLoading({
          success: (res) => {},
        });
      },
      fail: function (res) {
        console.error(res);
        wx.hideLoading({
          success: (res) => {},
        });
      },
    });
  },
  // 评论功能
  subMainCommentBtn() {
    this.setData({
      maincomment: "",
      mainCommentShow: true,
    });
  },
  delCommentIMg(e) {
    let val = e.target.dataset.index;
    this.data.imgList.splice(val, 1);
    this.setData({
      imgList: this.data.imgList,
    });
  },
  // 发送按钮
  subMainBtn(e) {
    let type = e.currentTarget.dataset.type;
    this.getReplyComments(type);
  },
  // 发送请求
  getReplyComments(type) {
    let that = this;
    let urlStr;
    let dataJson = {
      images: that.data.imgList,
      content: "",
    };
    console.log(type);
    if (type == "main") {
      if (app._isTextEmpty(this.data.maincomment)) {
        wx.showToast({
          title: "请输入评论内容",
          icon: "none",
          duration: 1000,
        });
        return;
      }
      urlStr = "plugin.article.api.comment.create-comment";
      dataJson.article_id = that.data.article_id;
      dataJson.content = that.data.maincomment;
    } else if (type == "reply") {
      if (app._isTextEmpty(this.data.replyContent)) {
        wx.showToast({
          title: "请输入评论内容",
          icon: "none",
          duration: 1000,
        });
        return;
      }
      urlStr = "plugin.article.api.comment.reply-comment";
      dataJson.content = that.data.replyContent;
      dataJson.comment_id = that.data.replyId;
    }
    wx.showLoading({
      title: '加载中',
      duration: 1000,
      icon: 'none'
    });
    app._getNetWork({
      url: app.getNetAddresss(urlStr),
      data: dataJson,
      success: function (res) {
        if (res.data.result == 1) {
          if (type == "main") {
            that.setData({
              commentPage: 1,
              mainCommentShow: false,
              replyshow: false,
              maincomment: ''
            });
            that.getComment();
          } else if (type == 'reply') {
            that.updateInfo(res.data.data, that.data.keyInd);
          }
        } else {
          console.error(res);
        }
        wx.hideLoading({
          success: (res) => {},
        });
      },
      fail: function (res) {
        wx.hideLoading({
          success: (res) => {},
        });
        console.error(res);
      },
    });
  },
  // 回复后更新数据
  updateInfo(data, ind) {
    console.log(data, ind);
    let arr = [];
    arr.push(data);
    if (this.data.commentList[ind].child) {
      this.data.commentList[ind].child.unshift(arr[0]);
    } else {
      this.data.commentList[ind].child = arr;
    }
    this.setData({
      commentList: this.data.commentList,
      mainCommentShow: false,
      replyshow: false,
      replyContent: ''
    });
  },
  // 上传图片
  uploaderFun(e) {
    wx.showLoading({
      title: "加载中",
    });
    let that = this;
    let urlStr = app.getNetAddresss("upload.uploadPic");
    wx.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        let photourl = tempFilePaths[0];
        wx.uploadFile({
          url: urlStr,
          filePath: photourl,
          name: "file",
          success(resdata) {
            var res = JSON.parse(resdata.data);
            wx.hideLoading();
            if (res.result == 1) {
              let imgList = that.data.imgList;
              imgList.push(res.data.img_url);
              that.setData({
                imgList,
              });
            } else {
              wx.showToast({
                icon: "none",
                title: res.msg,
                duration: 1500,
              });
            }
          },
        });
      },
      fail: function (res) {
        wx.hideLoading({
          success: (res) => {},
        });
      }
    });
  },
  replyshowClose() {
    this.setData({
      replyshow: false,
    });
  },
  // 遮罩关闭
  mainCommentShowClose() {
    this.setData({
      mainCommentShow: false,
    });
  },
  // 输入框事件 主评论文字
  maincommentinp(e) {
    let val = e.detail.value;
    this.setData({
      maincomment: val,
    });
  },
  replyContentinp(e) {
    let val = e.detail.value;
    this.setData({
      replyContent: val,
    });
  },
  //获取数据
  getData() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.article.api.article.get-article");
    urlStr += '&article_id=' + this.data.article_id;
    urlStr += '&share_uid=';
    app._getNetWork({
      url: urlStr,
      success: (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          res.data.audio_link = decodeURIComponent(res.data.audio_link);
          that.setData({
            dataInfo: res.data,
            is_liked: res.data.liked,
            like_num: res.data.like_num + res.data.virtual_like_num,
            read_num: res.data.read_num + res.data.virtual_read_num,
            codeUrl:res.data.miQrCodeUrl
          });
          innerAudioContext.src = encodeURI(this.data.dataInfo.audio_link);

          // this.innerAudioContext = wx.createAudioContext("myAudio");
          // this.innerAudioContext.setSrc(decodeURIComponent(res.data.audio_link))
          wx.setNavigationBarTitle({
            title: that.data.dataInfo.title ? that.data.dataInfo.title : ''
          });
          if (res.data.comment) {
            // 文章评论功能有开启才请求
            that.setData({
              comment: res.data.comment
            });
            that.getComment();
          }
        } else {
          that.setData({
            isShow: 0
          });
          if (res.data.msg == "您尚未购买该文章内容,无法观看") {
            wx.showModal({
              content: res.data.msg,
              showCancel:false,
              success:()=>{
                //要延时执行的代码
                wx.redirectTo({
                  url: "/packageD/article/articleList/articleList?article_id=" + that.data.article_id,
                });
              }
            })
          } else {
            wx.showModal({
              content: res.data.msg,
              showCancel:false,
              success:()=>{
                //要延时执行的代码
                wx.navigateBack({
                  delta: 1,
                });
              }
            })
          }
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  getComment() {
    let that = this;
    app._getNetWork({
      url: app.getNetAddresss("plugin.article.api.comment.comment-list"),
      data: {
        page: this.data.commentPage,
        article_id: this.data.article_id,
      },
      success: function (res) {
        if (res.data.result == 1) {
          let list = res.data.data.list.data;
          for (let i = 0; i < list.length; i++) {
            if (list[i].reply_num > 0) {
              list[i].commentShow = true;
            } else {
              list[i].commentShow = false;
            }
            list[i].commenMorePage = 1;
            list[i].child = [];
          }
          that.setData({
            last_page: res.data.data.list.last_page,
            commenMember: res.data.data.member,
            commentList: res.data.data.list.data,
            commentNum: res.data.data.num
          });
        } else {
          console.error(res);
        }
      },
      fail: function (res) {
        console.error(res);
      },
    });
  },
  tapbf(e) {
    if(this.data.bfstatus) {
      innerAudioContext.pause();
    }else {
      innerAudioContext.src = encodeURI(this.data.dataInfo.audio_link);
      innerAudioContext.play();
    }
    this.setData({
      bfstatus: !this.data.bfstatus,
    });
  },
  init() {
    innerAudioContext.onCanplay(() => {});
    innerAudioContext.onPlay(() => {
      console.log("开始播放");
      console.log(innerAudioContext.duration);
      this.setData({
        currentTime: this.realFormatSecond(innerAudioContext.duration),
        slmin: "0:00:00",
      });
    });
    innerAudioContext.onTimeUpdate(() => {
      setTimeout(() => {
        let smun = (innerAudioContext.currentTime / innerAudioContext.duration) * 100;
        var valueSlmin = parseInt(smun);
        // console.log(smun);
        this.setData({
          currentTime: this.realFormatSecond(innerAudioContext.duration),
          slmin: this.realFormatSecond(innerAudioContext.currentTime),
          valueSlmin: valueSlmin,
          audio_length: innerAudioContext.duration,
        });
      }, 1000);
    });
    innerAudioContext.onEnded((e)=>{
      console.log('播放结束')
      this.setData({
        valueSlmin:0,
        slmin: "0:00:00",
        bfstatus:false
      })
    })
    innerAudioContext.onError((res) => {
      wx.showToast({
        title: "播放错误",
        icon: "none",
      });
    });
  },
  sildein(e) {
    var setvalue = e.detail.value / 100;
    var long = this.data.audio_length * setvalue;
    console.log(long, setvalue);
    innerAudioContext.seek(long);
  },
  realFormatSecond(second) {
    var secondType = typeof second;

    if (secondType === "number" || secondType === "string") {
      second = parseInt(second);

      var hours = Math.floor(second / 3600);
      second = second - hours * 3600;
      var mimute = Math.floor(second / 60);
      second = second - mimute * 60;

      return hours + ":" + ("0" + mimute).slice(-2) + ":" + ("0" + second).slice(-2);
    } else {
      return "0:00:00";
    }
  },
  getQrCode() {
    let that = this;
    let urlStr = app.getNetAddresss("member.member.getArticleQr");
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            codeUrl: res.data
          });
        } else {
          console.log(res.msg);
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
});
